<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/18
 * Time: 23:05
 */

namespace app\api\controller\v1;

use app\api\controller\Common;
use app\common\lib\exception\ApiException;
use think\Log;

class Index extends Common
{

    /**
     * 获取首页接口
     * 1 头图 4 - 6
     * 2 推荐位列表 默认 40
     */
    public function index(){
        $heads = model('News')->getIndexHeadNormaNews(4);
        $heads = $this->getDealNews($heads);
        $positions = model('News')->getPositionsNormalNews(20);
        $positions = $this->getDealNews($positions);

        $result = [
            'heads' => $heads,
            'positions' => $positions
        ];

        return show(config('code.success'),'OK',$result, 200);
    }

    /**
     * 客户端初始化接口
     * 1、检测APP是否需要升级
     * @return ApiException|array
     */
    public function init(){
        //app_type 去 ent_version 查询
        try{
            $version = model('Version')->getLastNormalVersionByAppType($this->headers['app-type']);
        }catch (\Exception $e){
            return new ApiException($e->getMessage(), 401);
        }

        if(empty($version)){
            return new ApiException('error', 404);
        }

        if($version->version > $this->headers['version']){
            $version->is_update = $version->is_force == 1 ? 2 : 1;
        }else{
            $version->is_update = 0;  // 0 不更新， 1 需要更新   2 强制更新
        }

        //记录用户的基本信息
        $actives = [
            'version' => $this->headers['version'],
            'app_type' => $this->headers['app-type'],
            'did' => $this->headers['did'],
            'user_agent' => $this->headers['user-agent'],
            'create_time' => time(),
            'update_time' => time(),
        ];
        try {
            model('AppActive')->add($actives);
        }catch (\Exception $e){
            //todo
            Log::write($e->getMessage());
        }

        return show(config('code.success'), 'OK', $version, 200);

    }

}